package com.tdam2014.grupo3.db;

import java.util.ArrayList;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.tdam2014.grupo3.entities.PhotoSet;

public class PhotoSetDatabaseHelper extends DatabaseHelper {

	public PhotoSetDatabaseHelper(Context context) {
		super(context);
	}
	
	public ArrayList<PhotoSet> getPhotoSetList(String peopleNsid) {
		SQLiteDatabase db = this.getReadableDatabase();
		
		String query = "SELECT * FROM " + tblPhotoSet + " WHERE " + colPhotoSetPeopleNSID + "=? ORDER BY " + colPhotoSetCreated + " DESC";
		Cursor cursor = db.rawQuery(query, new String [] {peopleNsid});
		
		PhotoSet photoSet;
		ArrayList<PhotoSet> photoSets = new ArrayList<PhotoSet>();
		while (cursor.moveToNext()) {
			photoSet = new PhotoSet();
			photoSet.setId(cursor.getString(cursor.getColumnIndex(colPhotoSetID)));
			photoSet.setTitle(cursor.getString(cursor.getColumnIndex(colPhotoSetTitle)));
			photoSet.setDateCreated(new Date(cursor.getLong(cursor.getColumnIndex(colPhotoSetCreated))));
			photoSet.setCountPhotos(cursor.getInt(cursor.getColumnIndex(colPhotoSetCountPhotos)));
			
			photoSets.add(photoSet);
		}
		
		return photoSets;
	}
	
	public void savePhotoSets(ArrayList<PhotoSet> photoSets, String peopleNsid) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.beginTransaction();
		
		ContentValues cv = new ContentValues();
		for(PhotoSet photoSet : photoSets) {
			cv.put(colPhotoSetPeopleNSID, peopleNsid);
			cv.put(colPhotoSetTitle, photoSet.getTitle());
			cv.put(colPhotoSetCreated, photoSet.getDateCreated().getTime());
			cv.put(colPhotoSetCountPhotos, photoSet.getCountPhotos());
			
			if(existPhotoSet(photoSet.getId())) {
				db.update(tblPhotoSet, cv, colPhotoSetID + "=?", new String[] {photoSet.getId()});
			} else {
				cv.put(colPhotoSetID, photoSet.getId());
				db.insert(tblPhotoSet, null, cv);
			}
		}
		
		db.setTransactionSuccessful();
		db.endTransaction();
		db.close();
	}
	
	private boolean existPhotoSet(String id) {
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.query(tblPhotoSet, null, colPhotoSetID + "=?", new String[] {id}, null, null, null);
		return cursor.moveToFirst();
	}
	
	public int getPhotoSetCountPhotos(String id) {
		SQLiteDatabase db = this.getReadableDatabase();
		
		Cursor cursor = db.query(tblPhotoSet, new String[] {colPhotoSetCountPhotos}, colPhotoSetID + "=?", new String[] {id}, null, null, null);
		if(cursor.moveToFirst()) return cursor.getInt(cursor.getColumnIndex(colPhotoSetCountPhotos));
		else return -1;
	}
	
	public void updatePhotoSetCountPhotos(String id, int countPhotos) {
		SQLiteDatabase db = this.getWritableDatabase();
		
		ContentValues cv = new ContentValues();
		cv.put(colPhotoSetCountPhotos, countPhotos);
		db.update(tblPhotoSet, cv, colPhotoSetID + "=?", new String[] {id});
		
		db.close();
	}
}
